<template>
  <div>
    <van-cell
      v-for="(text, index) in suggestions"
      :key="index"
      :title="text"
      icon="search"
      @click="$emit('search', text)"
    >
      <span slot="title" v-html="highlight(text)"></span>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'

export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [],
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(function (val) {
        this.loadSearch(val)
        console.log(val)
      }, 200),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearch(q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
      } catch (err) {
        this.$toast('获取搜索数据失败,请稍后重试!!!')
      }
    },
    highlight(text) {
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(
        reg,
        `<span style="color:red">${this.searchText}</span>`
      )
    },
  },
}
</script>

<style lang="less" scoped></style>
